package com.lepu.app.fun.index.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.ImageCompressUtils;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.geneal.UploadMenuImage;
import com.core.lib.utils.main.FileUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.AppPhotoGridActivity;
import com.core.lib.utils.photo.PhotoInfo;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.index.adapter.AdapterIndexFileAddImage;
import com.lepu.app.main.activity.AppImageBroswerActivity;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.permission.callback.PermissionResultCallBack;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

public class IndexFileReportAddActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
		AsyncRequest, OnEditorActionListener {

	public static final int MAX_LENGTH_50 = 50;
	public static final int MAX_LENGTH_240 = 240;
	public static final int MAX_LENGTH_400 = 400;
	public static final int MAX_LENGTH_3000 = 3000;
	public static final int MAX_LENGTH_20000 = 20000;

	private static final String REQUEST_SEND_CONTENT = "request_send_content";
	private static final String REQUEST_SEND_IMAGE = "request_send_image";

	public static final int IMAGE_WIDTH = 500;
	public static final int IMAGE_HEIGHT = 500;

	private static final int MSG_SEND_CONTENT_SUCCESS = 10;
	private static final int MSG_SEND_CONTENT_FAIL = 11;

	private static final int MSG_SEND_IMAGE_FINISH = 20;
	private static final int MSG_SEND_IMAGE_FAIL = 21;

	private String mThreadID = "";

	private TextView mCountTextView = null;
	private CustomTopBarNew mTopbar = null;

	private EditText mContentEditText;
	private boolean mCanSend = true;

	private int mMaxLength = 0;

	private GridView mDataGridView = null;
	private AdapterIndexFileAddImage mDataAdapter = null;
	private ArrayList<String> mDataList = new ArrayList<String>();
	private ArrayList<String> mDataTempList = new ArrayList<String>();

	private int mSendImageIndex = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_file_report_add_activity);

		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		updateAddImages();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		if (!checkContent()) {
			finish(true);
		}
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
		mTopbar.setRightText("完成");
		mTopbar.setonTopbarNewLeftLayoutListener(this);
		mTopbar.setOnTopbarNewRightButtonListener(this);

		mContentEditText = (EditText) findViewById(R.id.contentEditText);

		mContentEditText.addTextChangedListener(mTextWatcher);
		mContentEditText.setOnEditorActionListener(this);
		mCountTextView = (TextView) findViewById(R.id.countTextView);

		mTopbar.setTopbarTitle("添加检查报告");
		mMaxLength = MAX_LENGTH_400;

		mContentEditText.setVisibility(View.VISIBLE);

		mContentEditText.setFilters(new InputFilter[] { new EmojiFilter(),new InputFilter.LengthFilter(mMaxLength) });

		mDataGridView = (GridView) findViewById(R.id.imageGridView);
		mDataAdapter = new AdapterIndexFileAddImage(this, mDataList);
		mDataGridView.setAdapter(mDataAdapter);

	}

	public void addImage() {

		PermissionUtil.getInstance().request(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,
						Manifest.permission.WRITE_EXTERNAL_STORAGE,},
				new PermissionResultCallBack() {
					@Override
					public void onPermissionGranted() {
						//
						UtilityBase.closeSoftInput(IndexFileReportAddActivity.this);

						String temp = SdLocal.getTempPhotoPath(IndexFileReportAddActivity.this, "temp_camera_icon");
						UploadMenuImage.getInstance(IndexFileReportAddActivity.this).setFilePath(temp);
						UploadMenuImage.getInstance(IndexFileReportAddActivity.this).setIsCut(false);
						UploadMenuImage.getInstance(IndexFileReportAddActivity.this).setIsPhotoDouble(true);
						UploadMenuImage.getInstance(IndexFileReportAddActivity.this).setPhotoDoubleNum(
								9 - mDataList.size());
						UploadMenuImage.getInstance(IndexFileReportAddActivity.this).showPopAddPhoto();
					}

					@Override
					public void onPermissionGranted(String... permissions) {
						if (permissions == null || permissions.length == 0) {
						}
					}

					@Override
					public void onPermissionDenied(String... permissions) {
						if (permissions != null) {

						}
					}

					@Override
					public void onRationalShow(String... permissions) {
						if (permissions != null) {
							UIHelper.showToast(IndexFileReportAddActivity.this, R.string.permission_tip);
							PermissionUtil.openSettingActivity(IndexFileReportAddActivity.this);
						}
					}
				});
	}

	public void removeImage(int index) {
		mDataList.remove(index);
		mDataAdapter.notifyDataSetChanged();
	}

	public void seeImage(int index) {
		String[] filePathArray = new String[mDataList.size()];

		for (int i = 0; i < mDataList.size(); i++) {
			filePathArray[i] = mDataList.get(i);
		}

		Intent intent = new Intent(this, AppImageBroswerActivity.class);
		intent.putExtra("isShowTopbar", true);
		intent.putExtra("index", index);
		intent.putExtra("filePathArray", filePathArray);
		startActivityForResult(intent, 100, false);
	}

	private void updateAddImages() {
		if (AppPhotoGridActivity.mSelectList.size() > 0) {
			for (PhotoInfo item : AppPhotoGridActivity.mSelectList) {

				String tempPath = item.getPath_absolute();
				mDataList.add(tempPath);
			}

			mDataAdapter.notifyDataSetChanged();
			PopUtil.getInstance().dismissPopWindow();
		}

		if (AppPhotoGridActivity.mSelectList != null) {
			AppPhotoGridActivity.mSelectList.clear();
		}
	}

	private void sendContent() {
		boolean flag = LoginUtil.jumpLogin(this);
		if (flag) {
			return;
		}

		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);

		String contentContent = contentEditText.getText().toString().trim();

		if (TextUtils.isEmpty(contentContent)) {
			UIHelper.showToast(this, "请输入内容");
			return;
		}

		if (!mCanSend) {
			UIHelper.showToast(this, "请输入少于400个字");
			return;
		}

		mDataTempList.clear();
		mSendImageIndex = 0;

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("Title", null);
			params.put("MeasureTime", null);

			params.put("Description", contentContent);
			params.put("ImageCount", mDataList.size());
			params.put("PatientID", loginInfo.UserID);
		} catch (Exception e) {
		}

		map.put("ht", params);

		showProgressDialog(false);
		ApiClient.http_post(Setting.getIndexFileReport(), map, null, this,REQUEST_SEND_CONTENT, true);
	}

	private void sendImage() {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("MRID", mThreadID);
			params.put("PatientID", "18697");
		} catch (Exception e) {
		}

		map.put("ht", params);

		String srcPath = mDataList.get(mSendImageIndex);
		String endPath = SdLocal.getTempPhotoPath(this,
				String.valueOf(System.currentTimeMillis()));

		boolean isException = false;
		try {
			ImageCompressUtils.CompressImageFile(srcPath, endPath);
		} catch (Exception e) {
			e.printStackTrace();
			isException = true;
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			isException = true;
		}

		if (isException) {
			mHandler.sendEmptyMessage(MSG_SEND_IMAGE_FAIL);
		} else {
			mDataTempList.add(endPath);
			Map<String, File> fileMap = new HashMap<String, File>();
			fileMap.put("Image", new File(endPath));

			ApiClient.http_post(Setting.getIndexFileReportImage(), map, fileMap, this,REQUEST_SEND_IMAGE, false);
		}
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
				case MSG_SEND_CONTENT_SUCCESS:

					if (mDataList.size() == 0) {
						hideProgressDialog();

						//刷新
						ObserverManager.getInstance().notify(ObserverConst.NOTIFY_FILE_REPORT_CHANGE, null, null);

						finish(true);
					} else {
						sendImage();
					}
					break;
				case MSG_SEND_CONTENT_FAIL:

					hideProgressDialog();
					break;
				case MSG_SEND_IMAGE_FINISH:

					if (mSendImageIndex >= mDataList.size()-1) {
						hideProgressDialog();

						ObserverManager.getInstance().notify(ObserverConst.NOTIFY_FILE_REPORT_CHANGE, null, null);

						finish(true);
					} else {
						mSendImageIndex++;
						sendImage();
					}
					break;
				case MSG_SEND_IMAGE_FAIL:
					hideProgressDialog();

					// 有一张图片上传失败，就不上传了
					break;

				default:
					break;
			}
		};
	};

	TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			int len = s.toString().length();

			if (len <= mMaxLength) {
				mCanSend = true;

				mCountTextView.setTextColor(getResources().getColor(R.color.color_text_black2));
			} else {
				mCanSend = false;

				mCountTextView.setTextColor(getResources().getColor(R.color.color_text_highlight));
			}
			mCountTextView.setText(String.format("(%d/%d)", len, mMaxLength));
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
									  int arg3) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	@Override
	public void onTopbarLeftLayoutSelected() {

		if (!checkContent()) {
			finish(true);
		}
	}

	@Override
	public void onTopbarRightButtonSelected() {
		sendContent();
	}

	private boolean checkContent() {
		boolean flag = false;

		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);

		String contentContent = contentEditText.getText().toString().trim();

		if ((!TextUtils.isEmpty(contentContent) || mDataList.size() > 0)) {
			flag = true;

			new MyDialog(this)
					.setMessage("退出此次编辑?")
					.setNegativeButton(R.string.app_cancel,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {

								}
							})
					.setPositiveButton(R.string.app_quit,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {

									finish(true);
								}
							}).create(null).show();
		}

		return flag;
	}

	public void onActivityResult(int requestCode, int resultCode,
								 final Intent data) {

		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 100) {
				int index = data.getExtras().getInt("index");
				removeImage(index);

			} else {
				UploadMenuImage.getInstance(this).onActivityResult(
						new CallBack() {
							@Override
							public void callBackSuccess(Object obj) {
								super.callBackSuccess(obj);

								// 只有照相回调回来，
								String tempPath = SdLocal.getTempPhotoPath(
										IndexFileReportAddActivity.this,
										"temp_camera_icon");

								String filePath = SdLocal.getTempPhotoPath(
										IndexFileReportAddActivity.this, String
												.valueOf(System
														.currentTimeMillis()));

								try {
									ImageCompressUtils.CompressImageFile(
											tempPath, filePath);

									// 删除照相临时文件
									File tempCameraFile = new File(tempPath);
									if (tempCameraFile.exists()) {
										FileUtilBase.deleteFile(tempCameraFile);
									}
									mDataList.add(filePath);
									mDataAdapter.notifyDataSetChanged();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}, requestCode, resultCode, data);
			}
		}
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_SEND_CONTENT)) {

			String result = (String) data;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");
				mThreadID = obj2.getString("MRID");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			mHandler.sendEmptyMessage(MSG_SEND_CONTENT_SUCCESS);
		} else if (object.equals(REQUEST_SEND_IMAGE)) {
			LogUtilBase.LogD(null, mSendImageIndex + "send success");

			File endFile = new File(mDataTempList.get(mSendImageIndex));
			if (endFile.exists()) {
				FileUtilBase.deleteFile(endFile);
			}
			mHandler.sendEmptyMessage(MSG_SEND_IMAGE_FINISH);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_SEND_CONTENT)) {
			mHandler.sendEmptyMessage(MSG_SEND_CONTENT_FAIL);
		}else if (object.equals(REQUEST_SEND_IMAGE)) {
			LogUtilBase.LogD(null, mSendImageIndex + "send image fail");

			File endFile = new File(mDataTempList.get(mSendImageIndex));
			if (endFile.exists()) {
				FileUtilBase.deleteFile(endFile);
			}
			mHandler.sendEmptyMessage(MSG_SEND_IMAGE_FAIL);
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
			case EditorInfo.IME_ACTION_SEND:

				sendContent();
				break;
		}
		return false;
	}
}
